package com.matrix.common.security.filter;

import com.matrix.common.constant.HeaderConstants;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;
import org.slf4j.MDC;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * @author 有点甜
 * @since 2025/8/5
 */
@Activate(group = CommonConstants.CONSUMER)
public class ConsumerAuthFilter implements Filter {

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            String userId = request.getHeader(HeaderConstants.USER_ID);
            String userRole = request.getHeader(HeaderConstants.USER_ROLE);

            if (userId != null) {
                RpcContext.getClientAttachment().setAttachment(HeaderConstants.USER_ID, userId);
            }
            if (userRole != null) {
                RpcContext.getClientAttachment().setAttachment(HeaderConstants.USER_ROLE, userRole);
            }
        }

        String traceId = MDC.get("traceId");
        if (traceId != null) {
            RpcContext.getClientAttachment().setAttachment(HeaderConstants.TRACE_ID, traceId);
        }

        return invoker.invoke(invocation);
    }
}
